package dbops

import (
	"database/sql"
	"fmt"
	"github.com/go-sql-driver/mysql"
)

var (
	dbConn *sql.DB
	err    error
)

func init() {

	dataSource, databaseName := "root:root123456@tcp(118.24.71.63:13306)", "streamWeb"
	dataSourceName := fmt.Sprintf("%s/%s?charset=utf8", dataSource, databaseName)
	dbConn, err = sql.Open("mysql", dataSourceName)
	if err != nil {
		goto Err
	}
	err = dbConn.Ping()
	if err == nil {
		goto End
	}
	if v, ok := err.(*mysql.MySQLError); ok && v.Number == 1049 {
		dbConn, err = sql.Open("mysql", dataSource+"/")
		if err != nil {
			goto Err
		}
		err = dbConn.Ping()
		if err != nil {
			goto Err
		}
		_, err = dbConn.Exec(fmt.Sprintf("create database if not exists %s character set utf8;", databaseName))
		if err != nil {
			goto Err
		}
		dbConn, err = sql.Open("mysql", dataSourceName)
		if err != nil {
			goto Err
		}
	}
End:
//数据库连接正常
	err = createTable(dbConn)

Err:
	if err != nil {
		if dbConn != nil {
			dbConn.Close()
		}
		panic(err)
	}

}

func createTable(db *sql.DB) (error) {
	if err = CreateUserTable(db); err != nil {
		return err
	}
	if err = CreateUserVideoTable(db); err != nil {
		return err
	}
	if err = CreateVideoCommentTable(db); err != nil {
		return err
	}
	if err = CreateSessionTable(db); err != nil {
		return err
	}
	return nil
}
